# -*- coding: utf-8 -*-
from django.conf import settings
import pymysql

strIP=settings.DATABASES["default"]["HOST"]
strUser=settings.DATABASES["default"]["USER"]
strPwd=settings.DATABASES["default"]["PASSWORD"]
strDb=settings.DATABASES["default"]["NAME"]
strPort=int(settings.DATABASES["default"]["PORT"])

def WordCrown(number,type):
    #type=callout,Local,ivr,group
    values=0
    conn = pymysql.connect(host=strIP, user=strUser, passwd=strPwd, db=strDb, port=strPort, charset="utf8")
    cursor = conn.cursor()
    if type.find("callout") > 0:
        cursor.execute("SELECT COUNT(*) pbx_calloutextension WHERE destination_number="+number)
        values += cursor.fetchall()[0][0]
    if type.find("Local") > 0:
        cursor.execute("SELECT COUNT(*) pbx_LocalExtension WHERE number=" + number)
        values += cursor.fetchall()[0][0]
    if type.find("ivr") > 0:
        cursor.execute("SELECT COUNT(*) pbx_ivr WHERE dn=" + number)
        values += cursor.fetchall()[0][0]
    cursor.close()
    conn.close()
    return values


def ReadSql(sql):
    conn = pymysql.connect(host=strIP, user=strUser, passwd=strPwd, db=strDb, port=strPort, charset="utf8")
    cursor = conn.cursor()
    cursor.execute(sql)
    # 使用featchall获得结果集（list）
    values = cursor.fetchall()
    cursor.close()
    conn.close()
    return  values

def ComSql(sql):
    conn = pymysql.connect(host=strIP, user=strUser, passwd=strPwd, db=strDb, port=strPort, charset="utf8")
    cursor = conn.cursor()
    try:
        cursor.execute(sql)
        conn.commit()
    except:
        print "conn.rollback()"
        conn.rollback()
    conn.close()
